/*
 * Package il.ac.biu.cs.grossmm.impl.server
 * File XmlBasedLoader.java
 * 
 * This is a part of presence service framework prototype. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package il.ac.biu.cs.grossmm.impl.server;

import il.ac.biu.cs.grossmm.xmlUtil.ElementParser;
import il.ac.biu.cs.grossmm.xmlUtil.Xml;
import il.ac.biu.cs.grossmm.xmlUtil.XmlException;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.w3c.dom.Element;

import il.ac.biu.cs.grossmm.api.server.Loader;
import il.ac.biu.cs.grossmm.api.server.Wrapped;
import il.ac.biu.cs.grossmm.api.server.Wrapper;
import il.ac.biu.cs.grossmm.api.server.NoSuchComponentException;


public class XmlBasedLoader implements Loader, ElementParser {
	private final Loader baseLoader;
	private Map<String, Element> xComponentMap
	 	= new HashMap<String, Element>();
	
	
	
	public XmlBasedLoader(Element xComponents, Loader baseLoader) {
		this.baseLoader = baseLoader;
		assert xComponents.getNodeName().equals("components");
		
		try {
			Xml.parseChldren(xComponents, "component",	this);
		} catch( Exception unexpected ) {
			assert(false);
		}
	}

	public void parse(Element e) throws XmlException {
		String name = e.getAttribute("name");
		// skip empty name? (no attr or "")
		xComponentMap.put(name, e);
	}
	
	public Set<String> getResourceNames() {
		return Collections.unmodifiableSet(xComponentMap.keySet());
	}

	public Wrapped load(Wrapper wrapper, Object hint) throws Exception {
		Element e = xComponentMap.get(hint);
		if( e == null )
			throw new NoSuchComponentException();
		
		XComponent xComponent = new XComponent(e, this);
		
		Wrapped wrapped = baseLoader.load(wrapper, xComponent.getCreationHint());
		wrapped.setLoader(xComponent.getMappedLoader());
		
		return wrapped;
	}
}
